<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :title="title"
    width="90%"
  >
    <el-form :inline="true" :model="infoForm" label-width="120px">
      <el-form-item :label="$t('isEnable')">
        <el-switch
          v-model="infoForm.status"
          :active-value="1"
          :inactive-value="0"
          :disabled="detailDisable"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </el-form-item>
    </el-form>
    <dynForm
      ref="dataForm"
      :form-disable="formDisable"
      :info-form="infoForm"
      :search-tags="searchTags"
      :select-list="selectList"
      :rules="rules"
    />
    <dynTable
      ref="dynTable"
      :loading="false"
      :table-data="tableData"
      :table-columns="tableColumns"
    />
    <pagination
      :page.sync="listQuery.page"
      :size.sync="listQuery.size"
      :total="total"
      @pagination="getList"
    />
    <span slot="footer">
      <el-button icon="el-icon-circle-close" @click="handleClose">{{
        $t("cancel")
      }}</el-button>
      <el-button
        v-btnThrottle="doSave"
        type="primary"
        icon="el-icon-receiving"
      >{{ $t("save") }}</el-button
      >
  </span></el-dialog
  >
</template>

<script>
import {
  getInfo,
  doUpdateValues,
  doUpdate
} from '@/api/auto-analyze-warning/analysisResult'
export default {
  name: 'AnalysisDetail',
  data() {
    return {
      dialogVisible: false,
      title: '',
      infoForm: {},
      listQuery: {
        page: 1,
        size: 10
      },
      total: 0,
      formDisable: false,
      detailDisable: false,
      selectList: {},
      searchTags: Object.freeze([
        { label: this.$t('customer'), prop: 'customer', tag: 'DynInput' },
        { label: this.$t('productName'), prop: 'productName', tag: 'DynInput' },
        {
          label: this.$t('packageType'),
          prop: 'packingFormCode',
          tag: 'DynInput'
        },
        { label: this.$t('processFlow'), prop: 'processNo', tag: 'DynInput' },
        {
          label: this.$t('processSpecificationNumber'),
          prop: 'processSpecificationNo',
          tag: 'DynInput'
        },
        { label: this.$t('Deviation'), prop: 'deviation', tag: 'DynInput' },
        { label: this.$t('cycle'), prop: 'cycle', tag: 'DynInput' },
        { label: this.$t('traceCycle'), prop: 'traceCycle', tag: 'DynInput' },
        { label: this.$t('SBLVersion'), prop: 'sblVer', tag: 'DynInput' },
        { label: this.$t('versionCycle'), prop: 'cycleVer', tag: 'DynInput' }
      ]),
      rules: {},
      tableData: [],
      tableColumns: Object.freeze([
        {
          prop: '',
          label: this.$t('index'),
          type: 'index',
          width: '50px',
          templete: (_scope) => {
            return (
              <span>
                {(this.listQuery.page - 1) * this.listQuery.size +
                  _scope.$index +
                  1}
              </span>
            )
          }
        },
        {
          prop: 'binNo',
          label: 'BinNo',
          sortable: true,
          filters: function(item, _this) {
            const arr = new Set();
            (_this.tableData || []).forEach((v) => {
              arr.add(v.binNo)
            })
            return Array.from(arr, (value) => ({ text: value, value: value }))
          },
          filterMethod: this.binNoHandler
        },
        {
          prop: 'binItem',
          label: 'BinName',
          sortable: true,
          filters: function(item, _this) {
            const arr = new Set();
            (_this.tableData || []).forEach((v) => {
              arr.add(v.binItem)
            })
            return Array.from(arr, (value) => ({ text: value, value: value }))
          },
          filterMethod: this.binNoHandler
        },
        {
          prop: 'category',
          label: 'Category',
          sortable: true,
          filters: function(item, _this) {
            const arr = new Set();
            (_this.tableData || []).forEach((v) => {
              arr.add(v.category)
            })
            return Array.from(arr, (value) => ({ text: value, value: value }))
          },
          filterMethod: this.binNoHandler
        },
        {
          prop: 'spec',
          label: 'Spec',
          width: '80px',
          templete: (_scope) => {
            return (
              <span>{_scope.row.spec}{'%'}</span>
            )
          },
          sortable: true
        },
        {
          prop: 'value',
          label: '3σ',
          width: '80px',
          templete: (_scope) => {
            if (!_scope.row.edit) {
              return <span>{_scope.row.value}</span>
            } else {
              return (
                <el-input
                  v-model={_scope.row.value}
                  size={'small'}
                  clearable
                ></el-input>
              )
            }
          },
          sortable: true
        },
        {
          prop: 'mean',
          label: this.$t('averageValue'),
          sortable: true, width: '140px'
        },
        {
          prop: 'calculateDate',
          label: this.$t('calculationDate'),
          sortable: true, width: '140px'
        },
        { prop: 'editTime', label: this.$t('editTime'), sortable: true, width: '140px' },
        { prop: 'editor', label: this.$t('editor'), width: '100px' },
        {
          prop: '',
          label: this.$t('action'),
          width: '60px',
          templete: (_scope) => {
            if (_scope.row.edit) {
              return (
                <el-link
                  type='primary'
                  underline={false}
                  disabled={this.detailDisable}
                  onClick={() => this.confirmEdit(_scope.row)}
                >
                  {this.$t('confirm')}
                </el-link>
              )
            } else {
              return (
                <el-link
                  type='primary'
                  underline={false}
                  onClick={() => {
                    _scope.row.edit = !_scope.row.edit
                  }}
                  disabled={this.detailDisable}
                >
                  {this.$t('edit')}
                </el-link>
              )
            }
          },
          fixed: 'right'
        }
      ])
    }
  },
  methods: {
    async handleOpen(row, isEdit = false) {
      if (row && row.id) {
        const res = await getInfo({
          id: row.id,
          cycleId: row.cycleId,
          cycleVer: row.cycleVer,
          sblId: row.sblId,
          sblVer: row.sblVer,
          ...this.listQuery
        })
        const { total, data } = res
        this.infoForm = Object.assign({}, row)
        this.tableData = data.map((v) => {
          return {
            ...v,
            edit: false
          }
        })
        this.total = total
        this.dialogVisible = true
        if (isEdit) {
          this.title = this.$t('details')
          this.formDisable = true
          this.detailDisable = true
        } else {
          this.title = this.$t('modify')
          this.formDisable = true
        }
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].$refs['dynForm'].clearValidate()
      })
    },
    doSave() {
      // this.$refs['dataForm'].$refs['dynForm'].validate((valid) => {
      //   if (valid) {
      if (this.infoForm.id) {
        doUpdate({
          id: this.infoForm.id,
          status: this.infoForm.status
        }).then((res) => {
          this.$betterTips(res, this.handleClose, this.handleUpdate)
        })
      }
      //   }
      // })
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    handleUpdate() {
      this.$emit('initList')
    },
    getList(page) {
      this.listQuery = page
      getInfo({ ...this.listQuery, ...this.infoForm }).then((res) => {
        const items = res.data
        this.tableData = items.map((v) => {
          return {
            ...v,
            edit: false
          }
        })
        this.total = res.total
      })
    },
    confirmEdit(row) {
      doUpdateValues({
        id: row.id,
        value: row.value
      }).then((res) => {
        if (res.code === 1) {
          row.edit = false
        }
      })
    },
    binNoHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    }
  }
}
</script>
